package br.com.massai.controller.listeners;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import br.com.massai.model.entity.Url;
import br.com.massai.view.utils.MassaiUtil;

public class PermissionListener implements PhaseListener {

	private static final long serialVersionUID = 6501603477559479320L;
	
	public PermissionListener() { }

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
        String currentPage = facesContext.getViewRoot().getViewId();
        boolean isLoginPage = currentPage.contains("/login.xhtml");

        if (!isLoginPage && MassaiUtil.isLogIn()) {
            if(!MassaiUtil.isAdmin() && !(currentPage.contains("/home.xhtml") || currentPage.contains("/index.xhtml") || currentPage.contains("passwordChange.xhtml"))){
	            for(Url u : MassaiUtil.urlPermissions())
	            	if(currentPage.contains(u.getUrl()))
	            		return;

	            NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
	            nh.handleNavigation(facesContext, null, "home");
            }
        }
	}

	@Override
	public void beforePhase(PhaseEvent event) {

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
}